package com.itheima.guava.samples.demo.functionDemo;


import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;

import java.util.HashMap;
import java.util.Map;

/**
 * 使用Predicate和Predicates进行对象过滤
 */
public class PredicateDemo {

    public static void main(String[] args) {
        testPredicates();
    }

    private static void testPredicates(){

        Predicate<Girl> agePredicate = new Predicate<Girl>() {
            @Override
            public boolean apply(Girl input) {
                return input.getAge() >= 18;
            }
        };

        Predicate<Girl> facePredicate = new Predicate<Girl>() {

            @Override
            public boolean apply(Girl input) {
                return input.getFace().equals("nice");
            }
        };

        Girl girl = new Girl(18, "ugly");

        //and：用于过滤两个Predicate都为true
        Predicate<Girl> andPredicate = Predicates.and(agePredicate, facePredicate);
        checkOut(andPredicate.apply(girl));

        //or：用于过滤其中一个Predicate为true
        Predicate<Girl> orPredicate = Predicates.or(agePredicate, facePredicate);
        checkOut(orPredicate.apply(girl));

        //not：用于将指定Predicate取反
        Predicate<Girl> noneAgePredicate = Predicates.not(agePredicate);
        andPredicate = Predicates.and(noneAgePredicate, facePredicate);
        checkOut(andPredicate.apply(girl));

        //compose: Function与Predicate的组合
        Map<String, Girl> map = new HashMap<String, Girl>() {
            //构造一个测试用Map集合
            {
                put("love", new Girl(18, "nice"));
                put("miss", new Girl(16, "ugly"));
            }
        };

        Predicate<Girl> predicate1 = Predicates.and(agePredicate, facePredicate);
        Function<String, Girl> function1 = Functions.forMap(map);
        Predicate<String> stringPredicate = Predicates.compose(predicate1, function1);
        System.out.println(stringPredicate.apply("love"));//true
        System.out.println(stringPredicate.apply("miss"));//false

    }

    /**
     * 判断输出
     *
     * @param flag
     */
    private static void checkOut(boolean flag) {
        if (flag) {
            System.out.println("She fits me");
        } else {
            System.out.println("She doesn't fit me");
        }
    }

}

